package trunk.utility;

import trunk.res.R;

import java.io.*;

/**
 * access file in a more convenient way
 * Created by IntelliJ IDEA.
 * User: yipeipei
 * Date: 11/28/11
 * Time: 10:53 PM
 * To change this template use File | Settings | File Templates.
 */
public class FileAccess {
    private BufferedReader bufferedReader;
    private String line;
    private boolean hasNextLineFlag;    //default false

    //constructor
    public FileAccess(File file){
        try {
            this.bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    //has next line test
    public boolean hasNextLine(){
        if(this.hasNextLineFlag){
            return true;
        }else{
            try {
                if((line = bufferedReader.readLine()) != null){
                    this.hasNextLineFlag = true;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return hasNextLineFlag;
    }

    //when hasNextLine returns true, use this method to get next line
    public String readLine(){
        this.hasNextLineFlag = false;
        return line;
    }

    //read whole file
    public String readInBulk(){
        StringBuffer stringBuffer = new StringBuffer();

        while (this.hasNextLine()){
            stringBuffer.append(this.readLine());
            stringBuffer.append("\n");
        }

        return stringBuffer.toString();
    }

    /*test case follows*/
    public static void main(String[] args){
        System.out.println(new FileAccess(R.file.MICROCODE).readInBulk());
    }
}
